package com.gcloud.controller.network.service.impl;

import com.gcloud.controller.ResourceProviders;
import com.gcloud.controller.network.dao.FloatingIpDao;
import com.gcloud.controller.network.dao.QosFipPolicyBindingDao;
import com.gcloud.controller.network.dao.QosPolicyDao;
import com.gcloud.controller.network.entity.FloatingIp;
import com.gcloud.controller.network.entity.QosFipPolicyBinding;
import com.gcloud.controller.network.entity.QosPolicy;
import com.gcloud.controller.network.provider.IQosProvider;
import com.gcloud.controller.network.service.IQosFipPolicyBindingService;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.header.enums.ResourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yaowj on 2018/10/30.
 */
@Service
public class QosFipPolicyBindingServiceImpl implements IQosFipPolicyBindingService {

    @Autowired
    private FloatingIpDao floatingIpDao;

    @Autowired
    private QosPolicyDao qosPolicyDao;

    @Autowired
    private QosFipPolicyBindingDao qosFipPolicyBindingDao;

    @Override
    public void bind(String fipId, String policyId) {

        QosPolicy qosPolicy = qosPolicyDao.getById(policyId);
        if(qosPolicy == null){
            throw new GCloudException("::qos 不存在");
        }
        FloatingIp fip = floatingIpDao.getById(fipId);
        if(fip == null){
            throw new GCloudException("::fip 不存在");
        }

        QosFipPolicyBinding bind = new QosFipPolicyBinding();
        bind.setPolicyId(policyId);
        bind.setFipId(fipId);
        qosFipPolicyBindingDao.save(bind);

        IQosProvider qosProvider = checkAndGetProvider(fip.getProvider());
        qosProvider.bindFip(fip.getProviderRefId(), qosPolicy.getProviderRefId());
    }

    private IQosProvider checkAndGetProvider(Integer providerType) {
        IQosProvider provider = ResourceProviders.checkAndGet(ResourceType.QOS, providerType);
        return provider;
    }
}
